package role

import (
	"context"
	"net/http"

	"go-zero-admin/apps/system/cmd/api/internal/svc"
	"go-zero-admin/apps/system/cmd/api/internal/types"
	"go-zero-admin/apps/system/cmd/rpc/syspb"
	"go-zero-admin/pkg/ctxdata"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListRoleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewListRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *ListRoleLogic {
	return &ListRoleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *ListRoleLogic) ListRole(req *types.ListRoleReq) (resp *types.ListRoleResp, err error) {
	listResp, err := l.svcCtx.RoleRpc.GetRoleList(l.ctx, &syspb.GetRoleListReq{
		Page: &syspb.PageReq{
			DateRange: req.DateRange,
			PageNum:   req.PageNum,
			PageSize:  req.PageSize,
			IsPage:    true,
		},
		Name:            req.RoleName,
		Status:          req.Status,
		IsDataScope:     true,
		DataScopeUserId: ctxdata.GetUidFromCtx(l.ctx),
	})
	if err != nil {
		return nil, err
	}

	// 处理数据
	roleList := make([]*types.SysRole, 0)
	for _, v := range listResp.GetList() {
		var role types.SysRole
		_ = copier.Copy(&role, v)
		roleList = append(roleList, &role)
	}

	return &types.ListRoleResp{
		PageResp: &types.PageResp{
			CurrentPage: listResp.GetPage().GetCurrent(),
			Total:       listResp.GetPage().GetTotal(),
		},
		List: roleList,
	}, nil
}
